//
//  MailViewController.m
//  ExchangeClient
//
//  Created by Антон on 03.12.12.
//  Copyright (c) 2012 Сураева Яна. All rights reserved.
//

#import "MailViewController.h"
#import "Mail.h"
#import "SendQueryToDB.h"
#import "SQLQueries.h"
#import "PDFViewer.h"
#import <sqlite3.h>
#import "MailCell.h"
#import "AttachViewController.h"

@interface MailViewController (){
    IBOutlet UIButton *showPDFButton;
}

@end

@implementation MailViewController
@synthesize folderName,requestHandlerInstance, mailcontent;

-(void) dealloc{


    [IDArray release];
    [bodyTypeArray release];
    [senderArray release];
    [dateArray release];
    [table release];
    [subjectArray release];
//    [scrollView release];
    [mailcontent release];
    [attachArray release];
    [super dealloc];
}


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [self initData];
    showPDFButton.hidden=YES;
    table.separatorStyle = UITableViewCellSeparatorStyleNone;
    [super viewDidLoad];
self.title=@"Mails";
    // Do any additional setup after loading the view from its nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}




-(void) initData{
    IDArray=[NSMutableArray new];
    bodyTypeArray=[NSMutableArray new];
    senderArray=[NSMutableArray new];
    dateArray=[NSMutableArray new];
    subjectArray=[NSMutableArray new];
    attachArray=[NSMutableArray new];

    static sqlite3 *database = nil;
    
    sqlite3_stmt *selectstmt;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory=[paths objectAtIndex:0];
    NSString *path=[documentsDirectory stringByAppendingPathComponent:@"FoldersForMail"];
;
    if (sqlite3_open([path UTF8String], &database) == SQLITE_OK) {
        
        
        NSString *sql = [[[NSString alloc]initWithString:[[@"SELECT docName, subject, date, bodyType, sender, body  FROM docs WHERE userName =\"" stringByAppendingString:folderName]stringByAppendingString:@"\""]]autorelease];

        if(sqlite3_prepare_v2(database, [sql cStringUsingEncoding:NSUTF8StringEncoding], -1, &selectstmt, NULL) == SQLITE_OK) {
            
            while(sqlite3_step(selectstmt) == SQLITE_ROW) {
                //NSInteger primaryKey = sqlite3_column_int(selectstmt, 0);
                NSString *folderObj = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 2)];
                NSString *subject=[NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 1)];
                NSString *name=[NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 0)];
                [IDArray addObject:name];
                [bodyTypeArray addObject:[NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 3)]];
                [senderArray addObject:[NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 4)]];
                [subjectArray addObject:subject];
                [dateArray addObject:folderObj];
                [attachArray addObject:[NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 5)]];
                
            }
        }
    }
    else
        sqlite3_close(database);
    
}



- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{

    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    return [IDArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    static NSString *CellIdentifier = @"MailCell";
    MailCell *cell = (MailCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        UIViewController *tempVC = [[UIViewController alloc] initWithNibName:@"MailCell" bundle:nil];
        cell = (MailCell*)tempVC.view;
        [tempVC release];
    }
    
    cell.nameMail.text=[subjectArray objectAtIndex:indexPath.row];
    cell.dataMail.text=[dateArray objectAtIndex:indexPath.row];
    
    if ([[senderArray objectAtIndex:indexPath.row] isEqualToString: @"(null)"])
        cell.sender.text=@"";
    else
        cell.sender.text=[senderArray objectAtIndex:indexPath.row];
    if ([[bodyTypeArray objectAtIndex:indexPath.row] isEqualToString: @"(null)"])
           {
        cell.bodyType.text=@"";
     }
        else
        cell.bodyType.text=[bodyTypeArray objectAtIndex:indexPath.row];

/*    if ([[attachArray objectAtIndex:indexPath.row] isEqualToString: @"(null)"])
    {
        cell.viewPDF.hidden=YES;
    }
    else{
        cell.viewPDF.hidden=NO;
        cell.bodyType.text=[attachArray objectAtIndex:indexPath.row];
    }
        
*/
    return cell;
}


-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    Mail *mail;
 //   mailcontent=[UITextView new];
    mail=[requestHandlerInstance getItemWithID:[IDArray objectAtIndex:indexPath.row]];
    [mailcontent setText:(NSString *)mail.body];
    if ([mail.attachments count] !=0){
        showPDFButton.hidden=NO;
        numberMail=indexPath.row;
    }
 //   [mailcontent setText:(NSString *)[mail.attachments objectAtIndex:0]];
    else
        showPDFButton.hidden=YES;
 //   [mailcontent setText:@"fjfkk"];
  //  [mail release];
/*
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory= [paths objectAtIndex:0];
    NSString *path= [documentsDirectory stringByAppendingPathComponent:@"729e24c112fa406a832e409175c98ccb.pdf"];
    NSFileManager *fileManager = [NSFileManager defaultManager];
	NSError *error;
	BOOL success = [fileManager fileExistsAtPath:path];
	if(!success) {
		NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"729e24c112fa406a832e409175c98ccb.pdf"];
		success = [fileManager copyItemAtPath:defaultDBPath toPath:path error:&error];
		
		if (!success)
			NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
	}
    [PDFViewer initing:scrollView :path];
    [scrollView reloadInputViews];
    */
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
/*
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{
	return [self.scrollView.subviews objectAtIndex:0];
}
- (void)viewDidUnload {
    [mailcontent release];
    mailcontent = nil;
    [self setMailcontent:nil];
     [super viewDidUnload];
}
*/


- (IBAction)showPDFButton:(id)sender {
    Mail *mail=[requestHandlerInstance getItemWithID:[IDArray objectAtIndex:numberMail]];
    AttachViewController *view2=[[[AttachViewController alloc]initWithNibName:@"AttachViewController" bundle:nil]autorelease];
    view2.mail=mail;
    view2.requestHandlerInstance=requestHandlerInstance;
    [self.navigationController pushViewController:view2 animated:YES];
}
@end
